from rest_framework import viewsets, status, filters
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from django.db.models import Q
from drf_spectacular.utils import extend_schema, extend_schema_view, OpenApiParameter
from drf_spectacular.types import OpenApiTypes
from .models import User, Role, Permission, Menu
from .serializers import (
    PermissionSerializer, RoleSerializer, UserManagementSerializer,
    MenuSerializer
)
from common.permissions import HasPermission, require_permission


class BaseViewSet(viewsets.ModelViewSet):
    """基础ViewSet，提供统一的响应格式"""
    permission_classes = [IsAuthenticated]
    
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        return Response({
            'success': True,
            'message': f'{self.get_model_name()}创建成功',
            'data': serializer.data
        }, status=status.HTTP_201_CREATED)
    
    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        return Response({
            'success': True,
            'message': f'{self.get_model_name()}更新成功',
            'data': serializer.data
        })
    
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response(status=status.HTTP_204_NO_CONTENT)
    
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return Response({
                'success': True,
                'data': {
                    'results': serializer.data,
                    'total': self.paginator.page.paginator.count,
                    'page': self.paginator.page.number,
                    'page_size': self.paginator.page_size,
                    'total_pages': self.paginator.page.paginator.num_pages
                }
            })

        serializer = self.get_serializer(queryset, many=True)
        return Response({
            'success': True,
            'data': serializer.data
        })
    
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({
            'success': True,
            'data': serializer.data
        })
    
    def get_model_name(self):
        return self.queryset.model._meta.verbose_name


@extend_schema_view(
    list=extend_schema(
        summary="获取权限列表",
        description="获取系统中所有权限的列表，支持分页、搜索和筛选",
        tags=['Permissions'],
        parameters=[
            OpenApiParameter('search', OpenApiTypes.STR, description='搜索关键词'),
            OpenApiParameter('code', OpenApiTypes.STR, description='权限代码筛选'),
            OpenApiParameter('page', OpenApiTypes.INT, description='页码'),
            OpenApiParameter('page_size', OpenApiTypes.INT, description='每页数量'),
        ]
    ),
    create=extend_schema(
        summary="创建权限",
        description="创建新的系统权限",
        tags=['Permissions']
    ),
    retrieve=extend_schema(
        summary="获取权限详情",
        description="根据ID获取权限的详细信息",
        tags=['Permissions']
    ),
    update=extend_schema(
        summary="更新权限",
        description="更新指定权限的信息",
        tags=['Permissions']
    ),
    destroy=extend_schema(
        summary="删除权限",
        description="删除指定的权限",
        tags=['Permissions']
    )
)
class PermissionViewSet(BaseViewSet):
    """权限管理ViewSet"""
    queryset = Permission.objects.all().order_by('id')
    serializer_class = PermissionSerializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['code']
    search_fields = ['name', 'code', 'description']
    ordering_fields = ['id', 'name', 'created_at']
    permission_classes = [IsAuthenticated]


class RoleViewSet(BaseViewSet):
    """角色管理ViewSet"""
    queryset = Role.objects.all().order_by('id')
    serializer_class = RoleSerializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['is_active']
    search_fields = ['name', 'code', 'description']
    ordering_fields = ['id', 'name', 'created_at']


class UserViewSet(BaseViewSet):
    """用户管理ViewSet"""
    queryset = User.objects.all().order_by('id')
    serializer_class = UserManagementSerializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['is_active', 'is_staff']
    search_fields = ['username', 'email', 'first_name', 'last_name']
    ordering_fields = ['id', 'username', 'date_joined']


class MenuViewSet(BaseViewSet):
    """菜单管理ViewSet"""
    queryset = Menu.objects.all().order_by('sort_order')
    serializer_class = MenuSerializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['is_active', 'parent']
    search_fields = ['name', 'path']
    ordering_fields = ['sort_order', 'created_at']
    
    @action(detail=False, methods=['get'])
    def tree(self, request):
        """获取菜单树结构"""
        menus = Menu.objects.filter(parent=None, is_active=True).order_by('sort_order')
        serializer = self.get_serializer(menus, many=True)
        return Response({
            'success': True,
            'data': serializer.data
        })
    
    @action(detail=False, methods=['get'])
    def user_menus(self, request):
        """获取当前用户可访问的菜单"""
        user = request.user
        
        # 获取用户的所有权限
        user_permissions = Permission.objects.filter(
            role__users=user
        ).distinct()
        
        # 获取用户可访问的菜单
        accessible_menus = Menu.objects.filter(
            permissions__in=user_permissions,
            is_active=True,
            parent=None
        ).distinct().order_by('sort_order')
        
        serializer = self.get_serializer(accessible_menus, many=True)
        return Response({
            'success': True,
            'data': serializer.data
        })
